<script setup lang="ts">
import { frequencyType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";
import Limits from "@/components/limits/Index.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  activityId = inject("activityId", { value: "" }),
  taskList = inject("taskList", { value: [] }),
  activityReadonly = inject("activityReadonly");

const form = ref<any>({
  partType: 0,
  freeType: 4,
  partTotalLimit: 0,
  lotteryTotalLimit: 0,
  lotteryLimitType: 0,
}),
  prizeAreas = ref<Array<any>>([]),
  taskConfig = ref<any>({
    lotteryConfig: 1,
    individual: 0,
    taskStyle: 0,
    rewardList: [{ scene: "TASK_GROUP", rewardNum: 1 }],
    taskList: [
      {
        status: 1,
        rewardList: [{ scene: "TASK", rewardNum: 1 }],
        accomText: "去完成",
        uid: "task-1",
      },
    ],
  }),
  currentTaskIndex = ref("task-1"),
  taskNum = ref(1);

const formRef = ref(),
  poolRef = ref(),
  taskRef = ref();

const rules = {
  partTotalNum: [
    { required: true, message: "请输入参与总次数", trigger: "blur" },
  ],
  groupAccomNum: [
    { required: true, message: "请填写完成任务数量", trigger: "blur" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit: null,
  });

  taskConfig.value =
    val.actTaskConfig ||
    Object.assign({}, taskConfig.value, {
      pageFlag: form.value.pageFlag,
      actId: activityId.value,
    });
  currentTaskIndex.value =
    taskConfig.value.taskList[0].id || taskConfig.value.taskList[0].uid;
  prizeAreas.value = val.prizeAreas || [];
  updateData();
};

// 新增任务项
const handleTabsAdd = () => {
  taskNum.value++;
  taskConfig.value.taskList.push({
    status: 1,
    rewardList: [],
    accomText: "去完成",
    uid: `task-${taskNum.value}`,
  });
  currentTaskIndex.value = `task-${taskNum.value}`;
  updateData();
};

// 删除任务项
const tabPaneRemove = (name: number | string) => {
  let index = taskConfig.value.taskList.findIndex(
    (item: any) => item.uid == name || item.id == name
  );
  taskConfig.value.taskList.splice(index, 1);
  currentTaskIndex.value =
    taskConfig.value.taskList[0].id || taskConfig.value.taskList[0].uid;

  updateData();
};

// 新增任务奖励
const addReward = (taskIndex?: number) => {
  // 单任务奖励
  if (taskConfig.value.taskStyle == 0) {
    if (!taskConfig.value.taskList[taskIndex as number].rewardList) {
      taskConfig.value.taskList[taskIndex as number].rewardList = [];
    }
    taskConfig.value.taskList[taskIndex as number].rewardList.push({
      rewardNum: 1,
      scene: "TASK",
    });
  }
  // 任务组奖励
  else {
    if (!taskConfig.value.rewardList) {
      taskConfig.value.rewardList = [];
    }
    taskConfig.value.rewardList.push({
      rewardNum: 1,
      scene: "TASK_GROUP",
    });
  }
};

// 删除任务奖励
const deleteReward = (taskIndex: number, RIndex?: number) => {
  ElMessageBox.confirm(`确认删除该奖励吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 单任务奖励
    if (taskConfig.value.taskStyle == 0) {
      taskConfig.value.taskList[taskIndex].rewardList.splice(RIndex, 1);
    } else {
      taskConfig.value.rewardList.splice(taskIndex, 1);
    }
  });
};

// 切换任务类型
const taskTypeChange = (taskIndex: number) => {
  let type = taskList.value.find(
    (item: any) => item.id === taskConfig.value.taskList[taskIndex].taskId[0]
  );
  taskConfig.value.taskList[taskIndex].taskIcon = type.taskImg || "";
  taskConfig.value.taskList[taskIndex].taskUrl = type.taskUrl || "";
  taskConfig.value.taskList[taskIndex].taskDesc = type.taskDescription || "";
  taskConfig.value.taskList[taskIndex].taskName = type.taskName || "";
  updateData();
};

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

// 添加奖池奖品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

const quotePrize = computed(() => {
  let rewardList: Array<any> = [];
  if (form.value.taskStyle == 0) {
    for (let i = 0; i < taskConfig.value.taskList.length; i++) {
      let reward = taskConfig.value.taskList[i].rewardList || [];
      rewardList = rewardList.concat(reward);
    }
  } else rewardList = taskConfig.value.rewardList || [];
  let prize = rewardList.filter((item: any) => {
    if (item.rewardType === "PRIZE") {
      return true;
    }
    return false;
  });
  if (prize && prize.length > 0) {
    return prize.map((item: any) => {
      return {
        prizeId: item.prizeId,
        poolId: item.prizeArea,
        specId: item.prizeSpec,
      };
    });
  }
  return [];
});

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (taskConfig.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actTaskConfig: taskConfig.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let actTaskConfig = {};

        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        // 无参与消耗自动填充免费次数
        detail.freeNum = null;
        detail.freeType = null;

        try {
          // 任务区域
          actTaskConfig = await checkTask();
          // 检查奖池
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actTaskConfig: actTaskConfig,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject("请检查基础信息配置");
      }
    });
  });
};

const checkTask = (): any => {
  return new Promise((resolve, reject) => {
    taskRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(taskConfig.value);
        if (detail.taskStyle == 1) {
          if (detail.rewardList.length == 0) {
            reject(`请配置任务奖励`);
          }
          detail.rewardList.forEach((reward: any) => {
            if (reward.lotteryAreaUid) reward.lotteryArea = "";
            if (reward.prizeAreaUid) reward.prizeArea = "";
            if (reward.prizeUid) reward.prizeId = "";
            if (reward.prizeSpecUid) reward.prizeSpec = "";
            if (reward.ticketAct === "local") reward.ticketAct = "";
          });
        }
        detail.taskList.forEach((item: any) => {
          if (detail.taskStyle == 0) {
            if (item.rewardList.length == 0) {
              currentTaskIndex.value = item.id || item.uid;
              reject(`请配置【${item.name}】任务奖励`);
            }
            item.rewardList.forEach((reward: any) => {
              if (reward.lotteryAreaUid) reward.lotteryArea = "";
              if (reward.prizeAreaUid) reward.prizeArea = "";
              if (reward.prizeUid) reward.prizeId = "";
              if (reward.prizeSpecUid) reward.prizeSpec = "";
              if (reward.ticketAct === "local") reward.ticketAct = "";
            });
          }

          if (item.taskId instanceof Array) {
            item.taskId = item.taskId[0];
          }
        });

        resolve(detail);
      } else reject(`请检查${form.value.name}配置`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" :disabled="activityReadonly">
    <template v-if="showPrizePool">
      <h3 class="collpase-title">中奖限制</h3>
      <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
        <el-radio-group v-model="form.lotteryTotalLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
        <template v-if="form.lotteryTotalLimit == 1">
          <el-form-item label-width="10px" prop="lotteryTotalNum">
            <EasyNumberInput v-model="form.lotteryTotalNum" :min="1" :max="9999" :precision="0" unit="次" />
          </el-form-item>
        </template>
      </el-form-item>
      <el-form-item label="中奖次数：">
        <el-radio-group v-model="form.lotteryLimitType">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.lotteryLimitType == 1">
        <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
          每人&nbsp;&nbsp;
          <el-select v-model="limit.type" placeholder="请选择" style="width: 100px">
            <el-option v-for="(item, key) in frequencyType" :label="item" :value="Number(key)" /> </el-select>&nbsp;&nbsp;
          最多
          <el-form-item label-width="10px" :prop="`lotteryLimit.${index}.limitNum`" :rules="[
            { required: true, message: '请填写限制次数', trigger: 'blur' },
          ]">
            <EasyNumberInput v-model="limit.limitNum" :min="1" :max="9999" unit="次" :precision="0"></EasyNumberInput>
          </el-form-item>
        </div>
      </el-form-item>
    </template>
  </el-form>
  <el-form ref="taskRef" :model="taskConfig" :rules="rules" label-width="auto" :disabled="activityReadonly">
    <h3 class="collpase-title">任务配置</h3>
    <!-- <el-form-item label="千人千面：">
      <el-switch
        v-model="taskConfig.individual"
        inline-prompt
        active-text="开启"
        inactive-text="关闭"
        :active-value="1"
        :inactive-value="0"
      />
    </el-form-item> -->
    <el-form-item label="任务形式：">
      <el-radio-group v-model="taskConfig.taskStyle">
        <el-radio :label="0">单任务</el-radio>
        <el-radio :label="1">任务组</el-radio>
      </el-radio-group>
    </el-form-item>
    <template v-if="taskConfig.taskStyle == 1">
      <el-form-item label="完成任务奖励：">
        完成
        <el-form-item label-width="10px" prop="groupAccomNum">
          <EasyNumberInput v-model="taskConfig.groupAccomNum" :min="1" :max="9999" unit="个" :precision="0"
            @change="updateData" />
        </el-form-item>任务，奖励
      </el-form-item>
      <el-form-item>
        <div>
          <div v-for="(reward, RIndex) in taskConfig.rewardList" class="flex-container">
            <RewardSelector v-model="taskConfig.rewardList[RIndex]" :subType="form.subType" :lottery="true"
              :prizeAreas="prizeAreas" :prefix="`rewardList.${RIndex}.`" @change="updateData" @addPool="addPool"
              @addPrize="addPoolPrize" />
            <el-button type="primary" icon="delete" circle style="margin-left: 10px"
              @click="deleteReward(RIndex)"></el-button>
          </div>
          <el-button type="primary" icon="plus" @click="addReward">添加奖励</el-button>
        </div>
      </el-form-item>
    </template>
    <div class="tabs-add">
      <el-button type="primary" icon="plus" @click="handleTabsAdd">添加任务</el-button>
    </div>
    <el-tabs v-model="currentTaskIndex" type="card" @tab-remove="tabPaneRemove">
      <el-tab-pane v-for="(task, index) in taskConfig.taskList" :label="task.taskName || `任务-${index}`" :key="index"
        :name="task.id || task.uid" :closable="!task.id && taskConfig.taskList.length > 1">
        <el-form-item label="状态：">
          <el-switch v-model="task.status" inline-prompt active-text="上架" inactive-text="下架" :active-value="1"
            :inactive-value="0" />
        </el-form-item>
        <el-form-item class="cascader" label="选择任务：" :prop="`taskList.${index}.taskId`" :rules="[
          { required: true, message: '请选择任务', trigger: 'change' },
        ]">
          <el-cascader v-model="task.taskId" :options="taskList" :props="{ value: 'id', label: 'taskName' }"
            @change="taskTypeChange(index)" />
        </el-form-item>
        <el-form-item label="任务图标：" :prop="`taskList.${index}.taskIcon`" :rules="[
          { required: true, message: '请上传任务图标', trigger: 'change' },
        ]">
          <Upload v-model="task.taskIcon" file-path="task/" list-type="picture-card" @success="updateData">
            <el-icon>
              <Plus />
            </el-icon>
          </Upload>
        </el-form-item>
        <el-form-item label="任务名称：" :prop="`taskList.${index}.taskName`" :rules="[
          { required: true, message: '任务名称不能为空', trigger: 'blur' },
        ]">
          <el-input v-model="task.taskName" :minlength="2" :maxlength="30" show-word-limit @change="updateData"
            placeholder="请填写任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务描述：" :prop="`taskList.${index}.taskDesc`">
          <el-input v-model="task.taskDesc" :minlength="0" :maxlength="30" show-word-limit placeholder="请填写任务描述"
            @change="updateData"></el-input>
        </el-form-item>
        <el-form-item v-if="taskConfig.taskStyle == 0" label="完成任务奖励：">
          <div>
            <div v-for="(reward, RIndex) in task.rewardList" class="flex-container">
              <RewardSelector v-model="task.rewardList[RIndex]" :subType="form.subType" :lottery="true"
                :prizeAreas="prizeAreas" :prefix="`taskList.${index}.rewardList.${RIndex}.`" @change="updateData"
                @addPool="addPool" @addPrize="addPoolPrize" />
              <el-button type="primary" icon="delete" circle style="margin-left: 10px"
                @click="deleteReward(index, RIndex)"></el-button>
            </div>
            <el-button type="primary" icon="plus" @click="addReward(index)">添加奖励</el-button>
          </div>
        </el-form-item>
        <el-form-item label="去完成任务文案：" :prop="`taskList.${index}.accomText`" :rules="[
          {
            required: true,
            message: '请填写去完成任务文案',
            trigger: 'blur',
          },
        ]">
          <el-input v-model="task.accomText" :maxlength="5" show-word-limit placeholder="请输入"
            @change="updateData"></el-input>
        </el-form-item>
        <!-- <el-form-item label="参与限制：">
          <Limits
            v-model="task.viewOriginal"
            :options="[
              'timeLimit',
              'groupLimit',
              'tagLimit',
              'activityLimit',
              'vipLimit',
            ]"
          ></Limits>
        </el-form-item> -->
      </el-tab-pane>
    </el-tabs>
  </el-form>
  <PrizePool ref="poolRef" v-model="prizeAreas" :poolType="showPrizePool ? [1, 2] : [2]" :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag" :quote="quotePrize" @change="updateData"></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;

  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }

  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.tabs-add {
  float: right;
  position: relative;
  z-index: 1;
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.flex-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.cascader {
  :deep(.el-cascader) {
    .el-input .el-input__suffix-inner .el-icon {
      &::before {
        display: none;
      }
    }
  }
}
</style>
